package com.usermanage.ServiceImpl;

import com.usermanage.Mapping.GroupMapping;
import com.usermanage.Mapping.PermissionMapping;
import com.usermanage.Mapping.UserMapping;
import com.usermanage.SecurityConfig.SpringSecurityUtils;
import com.usermanage.SecurityConfig.UserDetail;
import com.usermanage.Service.GroupMemberService;
import com.usermanage.Service.SecurityService;
import com.usermanage.Service.UserService;
import com.usermanage.beanParam.GroupBean;
import com.usermanage.beanParam.PermissionBean;
import com.usermanage.beanParam.UserBean;
import com.usermanage.dataDao.JpaDao;
import com.usermanage.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.jni.Mmap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by 過客 on 2018/3/9
 */
@Slf4j
@Service("userService")
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapping userMapping;

    @Resource
    private GroupMapping groupMapping;

    @Autowired
    private SecurityService securityService;

    @Resource
    private PermissionMapping permissionMapping;

    @Resource
    private GroupMemberService groupMemberService;
    @Resource
    private JpaDao jpaDao;

    @Override
    public JsonData login(HttpServletRequest request, String email, String password, String url,String resource) throws Exception {
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        if (userDetail == null) {//用户没有登陆
            //1、根据提交数据获取用户信息，验证用户存在
//            String psd = StringUtil.EncoderByMd5(password);
//            Map<String,String> map = new HashMap();
//            map.put("account",email);
//            map.put("password",psd);
//            String result = HttpUtil.httpPost(StaticUtil.changeCenter+"/validateLogon.json",map);
//            Map mapResult = StringUtil.JsonToMap(result);
//            if((Integer)mapResult.get("errCode")==0){
//                return JsonData.fail(mapResult.get("errMsg").toString());
//            }
//            securityService.autologinrequest(email, psd, request);
            List<UserBean> list = StringUtil.convertListMapToListBean(userMapping.findUserInfoByEmail(email), UserBean.class);
//            //2、表示用户不存在
            if (list.size() == 0) {
//                return JsonData.fail("用户不存在，请核对账号信息。");
            } else {
                String psd = StringUtil.EncoderByMd5(password);
                //3、表示用户存在  然后Security登陆
                if(StringUtils.isNotBlank(resource)){
                    if(resource.equals("Wechat")){
                        securityService.autologinrequest(email, password, request);
                    }else{
                        securityService.autologinrequest(email, StringUtil.EncoderByMd5(password), request);
                    }
                }else{
                    securityService.autologinrequest(email, StringUtil.EncoderByMd5(password), request);
                }


                userDetail = SpringSecurityUtils.getCurrentUser();
                if (userDetail == null) {
                    return JsonData.fail("登陆异常！");
                } else {
                    int type = 1;

                    StringBuffer stringBuffer = new StringBuffer();
//                    List<Map> listMap = new ArrayList<>();
                    //1、把相关信息封装到登陆用户的会话信息中
                    UserBean bean = list.get(0);
                    userDetail.setGroup_id(bean.getGroup_id());
                    userDetail.setParent_id(bean.getParent_id());
                    userDetail.setCompany_id(bean.getCompany_id());
                    userDetail.setUser_type(bean.getUser_type());
                    userDetail.setCompany_type(bean.getType());
                    userDetail.setList(getPermissionList());
                    return JsonData.success(url);
                }
            }
            return JsonData.success(url);
        } else {
//            List<Map> list = groupMapping.getUserGroupListByUserId(userDetail.getId().toString());
//            StringBuffer stringBuffer = new StringBuffer();
//            for (int i = 0; i < list.size(); i++) {
//                stringBuffer.append(list.get(i).get("id")).append(",");
//            }
            return JsonData.success(url);
        }
    }

    @Override
    public JsonData oapiLogin(HttpServletRequest request, String userId, String url) {

        Map map = userMapping.findUserDetail(userId);
        List<UserBean> list = StringUtil.convertListMapToListBean(userMapping.findUserInfoByEmail(map.get("email").toString()), UserBean.class);
        securityService.autologinrequest(map.get("email").toString(), map.get("password").toString(), request);
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        //3、表示用户存在  然后Security登陆
        userDetail = SpringSecurityUtils.getCurrentUser();
        if (userDetail == null) {
            return JsonData.fail("登陆异常！");
        } else {
            int type = 1;
            StringBuffer stringBuffer = new StringBuffer();
            UserBean bean = list.get(0);
            userDetail.setCompany_id(bean.getCompany_id());
            userDetail.setUser_type(bean.getUser_type());
            userDetail.setCompany_type(bean.getType());
            return JsonData.success(url);
        }
    }

    @Override
    public Optional getUserDetail(String userId) {
        //1、判断是获取登陆用户信息，还是其他用户信息
        int id = 0;
        if (StringUtils.isBlank(userId)) {
            id = SpringSecurityUtils.getCurrentUser().getId();
        } else {
            id = Integer.valueOf(userId);
        }
        //得到用户详情
        Optional<UserBean> optional = userMapping.findById(id);
//        if (optional.isPresent()){
//            UserBean bean = optional.get();
////            List<GroupBean> list = StringUtil.convertListMapToListBean(groupMapping.getUserGroupListByUserId(String.valueOf(id)),GroupBean.class);
//             return bean;
//        }else{
        return optional;
//        }
    }

    @Override
    public UserBean save(UserBean userBean) throws Exception {
//        userBean.setUser_password(StringUtil.EncoderByMd5(userBean.getUser_password()));
//        userBean.setCreat_time(new Date());
//        userBean.setUser_state("11");
        UserBean result = userMapping.save(userBean);
        return result;
    }

    @Override
    public Boolean isExisit(UserBean bean) {
        Example<UserBean> example = Example.of(bean);
        boolean bool = userMapping.exists(example);
        return bool;
    }

    @Override
    public List<UserBean> getAllUserList(String key, String page, String size) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT u.* FROM  u_user u   WHERE u.user_type != 99  and u.user_type != 88");
        buffer.append(" and company_id = ").append(SpringSecurityUtils.getCurrentUser().getCompany_id());
        if (StringUtils.isNotBlank(key)) {
            buffer.append(" and (u.user_name like '%").append(key).append("%' or u.user_email like '%").append(key).append("%' or u.user_phone like '%").append(key).append("%')");
        }
        buffer.append(" order by id desc limit ").append((Integer.valueOf(page) - 1) * Integer.valueOf(size)).append(",").append(size);
        List<UserBean> list = jpaDao.getListByPage(buffer.toString(),UserBean.class);
        return list;
    }


    @Override
    public int getAllUserListCount(String key) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT count(1) FROM  u_user u   WHERE u.user_type != 99  and u.user_type != 88");
        buffer.append(" and company_id = ").append(SpringSecurityUtils.getCurrentUser().getCompany_id());
        if (StringUtils.isNotBlank(key)) {
            buffer.append(" and (u.user_name like '%").append(key).append("%' or u.user_email like '%").append(key).append("%' or u.user_phone like '%").append(key).append("%')");
        }
        return jpaDao.getListCountByPage(buffer.toString());
    }

    @Override
    public List<UserBean> getCustomUserList(String key, String page, String size) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT u.* FROM  u_user u   WHERE u.user_type = 88 ");
        if (StringUtils.isNotBlank(key)) {
            buffer.append(" and (u.user_name like '%").append(key).append("%' or u.user_email like '%").append(key).append("%' or u.user_phone like '%").append(key).append("%')");
        }
        buffer.append(" order by id desc limit ").append((Integer.valueOf(page) - 1) * Integer.valueOf(size)).append(",").append(size);
        List<UserBean> list = jpaDao.getListByPage(buffer.toString(),UserBean.class);
        return list;
    }


    @Override
    public int getCustomUserListCount(String key) {
        StringBuffer buffer = new StringBuffer();
        buffer.append("SELECT count(1) FROM  u_user u   WHERE u.user_type = 88 ");
        if (StringUtils.isNotBlank(key)) {
            buffer.append(" and (u.user_name like '%").append(key).append("%' or u.user_email like '%").append(key).append("%' or u.user_phone like '%").append(key).append("%')");
        }
        return jpaDao.getListCountByPage(buffer.toString());
    }

    /**
     * 查询系统所有用户
     *
     * @return
     */
    @Override
    public List<UserBean> getAllUserList() {
        StringBuffer buffer = new StringBuffer();
        buffer.append("select * from u_user where user_state = 11 ");
        List<UserBean> list = jpaDao.getListByPage(buffer.toString(),UserBean.class);
        return list;
    }

    /**
     * 根据当前登陆用户信息获取权限列表
     */
    @Override
    public List<PermissionBean> getPermissionList() {
        UserDetail userDetail = SpringSecurityUtils.getCurrentUser();
        Set set = new HashSet<>();
        List<Integer> group = groupMemberService.findUserGroup(String.valueOf(userDetail.getId()), userDetail.getCompany_id());
        List<Map> list = new ArrayList<>();
        for (int i = 0; i < group.size(); i++) {
            List<Map> pList = permissionMapping.findPermissionListByGroupId(group.get(i).toString());
            for (int j = 0; j < pList.size(); j++) {
                list = StringUtil.mapCopy(pList, list);
            }
        }
        for (int i = 0; i < list.size(); i++) {
            set.add(list.get(i));
        }
        List<Map> perssionList = new ArrayList<>(set);
        List<PermissionBean> listBean = StringUtil.convertListMapToListBean(perssionList, PermissionBean.class);//查看该组下是否有权限
        Collections.sort(listBean, new Comparator<PermissionBean>() {
            @Override
            public int compare(PermissionBean o1, PermissionBean o2) {
                Integer id1 = Integer.valueOf(o1.getId());//
                Integer id2 = Integer.valueOf(o2.getId()); //
                return id1.compareTo(id2);
            }
        });
        return listBean;
    }

    @Override
    public Optional<UserBean> findById(int id) {
        return userMapping.findById(id);
    }

    @Override
    public UserBean findUserDetail(String id) throws Exception {
        Map map = userMapping.findUserDetail(id);
        if(map.isEmpty()){
            return null;
        }else{
            return StringUtil.JsonToBean(StringUtil.ObjectToJson(map), UserBean.class);
        }
    }

    @Override
    public List<UserBean> findUserByUserNameAndCompanyId(String name, String companyId) {
        List<Map> mapList = userMapping.findUserByUserNameAndCompanyId(name, companyId);
        List<UserBean> list = StringUtil.convertListMapToListBean(mapList, UserBean.class);
        return list;
    }

    @Override
    public List<UserBean> findUserByCompanyId(String companyId) {
        List<Map> mapList = userMapping.findUserByCompanyId(companyId);
        List<UserBean> list = StringUtil.convertListMapToListBean(mapList, UserBean.class);
        return list;
    }

    @Override
    public List<UserBean> findAllUserByGroupId(String groupId) {
        return userMapping.findAllUserByGroupId(groupId);
    }

    @Override
    public List<UserBean> findAllUserByUserName(String name) {
        List<Map> mapList = userMapping.findAllUserByUserName(name);
        List<UserBean> list = StringUtil.convertListMapToListBean(mapList, UserBean.class);
        return list;
    }


    @Override
    public JsonData loginPort(String email) throws Exception {
        Map map = userMapping.findUserDetailForPort(email);
        log.info("用户接口信息：" + map);
        if (map.size() > 0) {
            return JsonData.success(map);
        }
        return JsonData.fail("登陆异常，用户不存在，或账号密码错误！");
    }

    /**
     * 第三方接口登陆获取用户信息
     *
     * @param user_name
     * @return
     * @throws Exception
     */
    @Override
    public Map findUserIdForPort(String user_name,String companyId) throws Exception {
        return userMapping.findUserIdForPort(user_name,companyId);
    }


}
